package com.demo.esper.listener;

import com.alibaba.fastjson.JSON;
import com.demo.service.EsperService;
import com.demo.uitls.SpringContextHolder;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.StatementAwareUpdateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class EsperMatchedListener implements StatementAwareUpdateListener {

    private final Logger logger = LoggerFactory.getLogger(EsperMatchedListener.class);


    @Override
    public void update(EventBean[] newEvents, EventBean[] oldEvents, EPStatement statement, EPServiceProvider epServiceProvider) {
        EventBean eventBean = newEvents[0];
        Map<String, Object> result = (Map<String, Object>) eventBean.getUnderlying();
        logger.info("Esper matched statement:{}", statement.getText());
        logger.info("Esper result:{}", JSON.toJSONString(result));
        Long eventId = (Long) result.getOrDefault("eventId", 0L);
        EsperService esperService = SpringContextHolder.INSTANCE.getBean(EsperService.class);
        if (eventId != null && esperService != null) {
            esperService.updateEsperRecord(eventId, result);
        }

    }
}
